<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>参数管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->

    <el-card>
      <!-- 消息提示 -->
      <el-alert
        :closable="false"
        show-icon
        title="注意： 只能使用三级相关参数"
        type="warning"
      >
      </el-alert>
      <!-- 商品选择分类区 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <!-- options 数据源 -->
          <el-cascader
            v-model="setcateList"
            clearable
            :options="setedCates"
            :props="{
              checkStrictly: true,
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children',
            }"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs栏 -->
      <el-row>
        <el-col>
          <el-tabs v-model="activeName" @tab-click="handleChange">
            <el-tab-pane label="动态参数" name="many">
              <!-- 动态按钮 -->
              <el-button
                type="primary"
                :disabled="disablebtn"
                @click="AddParamsVisble = true"
                >添加动态参数</el-button
              >
              <!-- 动态参数表格 -->
              <el-table :data="manyParamsData" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-tag
                      v-for="(item, ind) in scope.row.attr_vals"
                      :key="ind"
                      closable
                      @close="delTag(ind, scope.row)"
                    >
                      {{ item }}</el-tag
                    >
                    <!-- 放一个新增按钮 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.addinputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="addTag(scope.row)"
                      @blur="addTag(scope.row)"
                    >
                    </el-input>
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>

                <!-- 索引列 -->
                <el-table-column type="index"> </el-table-column>
                <el-table-column label="参数名称" prop="attr_name">
                </el-table-column>
                <el-table-column label="操作">
                  <!-- 按钮作用域插槽 -->
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      icon="el-icon-edit"
                      @click="showeditclick(scope.row)"
                      >编辑</el-button
                    >
                    <el-button type="danger" icon="el-icon-delete"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only">
              <!-- 静态按钮 -->
              <el-button
                type="primary"
                :disabled="disablebtn"
                @click="AddParamsVisble = true"
                >添加静态属性</el-button
              >
              <!-- 静态参数表格 -->
              <el-table :data="onlyParamsData" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-tag
                      v-for="(item, ind) in scope.row.attr_vals"
                      :key="ind"
                      closable
                      @close="delTag(ind, scope.row)"
                    >
                      {{ item }}</el-tag
                    >
                    <!-- 放一个新增按钮 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.addinputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="addTag(scope.row)"
                      @blur="addTag(scope.row)"
                    >
                    </el-input>
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"> </el-table-column>
                <el-table-column label="属性名称 " prop="attr_name">
                </el-table-column>
                <el-table-column label="操作">
                  <!-- 按钮作用域插槽 -->
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      icon="el-icon-edit"
                      @click="showeditclick(scope.row)"
                      >编辑</el-button
                    >
                    <el-button type="danger" icon="el-icon-delete"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>

    <!-- 参数显示对话框 -->
    <el-dialog
      :title="'添加' + TlietText"
      :visible.sync="AddParamsVisble"
      width="50%"
      @close="addDialog"
    >
      <!-- 表单内荣 -->
      <el-form
        :model="addForm"
        :rules="addFormRoles"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="TlietText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddParamsVisble = false">取 消</el-button>
        <el-button type="primary" @click="AddParamsList">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改显示对话框 -->
    <el-dialog
      :title="'修改' + TlietText"
      :visible.sync="editParamsVisble"
      width="50%"
    >
      <!-- 修改表单内荣 -->
      <el-form
        :model="editForm"
        :rules="editFormRoles"
        ref="editFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="TlietText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsVisble = false">取 消</el-button>
        <el-button type="primary" @click="EditParamsList">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  // 钩子函数
  created () {
    // 调用获取商品数据
    this.getCateList()
  },
  data () {
    return {
      // 修改表单数据--------------------
      // 修改参数表单数据对象
      editForm: {
        attr_name: '',
        attr_sel: 0,
        attrID: -1 // 要修改的参数id
      },
      // 修改效验添加表单参数对象
      editFormRoles: {
        attr_name: [{ required: true, message: '请输入名字', trigger: 'blur' }]
      },
      // 控制修改和显示对话框的属性
      editParamsVisble: false,

      // tab 栏选中的动态属性或者静态属性-----------------
      activeName: 'many',
      //  下拉框中选中分类的id
      setcateList: [],
      // 父类下拉数据框
      setedCates: [],
      // 保存的动态参数
      manyParamsData: [],
      // 保存的静态参数
      onlyParamsData: [],
      // 控制添加和显示对话框的属性
      AddParamsVisble: false,
      // 添加参数表单数据对象
      addForm: {
        attr_name: '',
        attr_sel: 0 // 参数类型 many only
      },
      // 效验添加表单参数对象
      addFormRoles: {
        attr_name: [{ required: true, message: '请输入名字', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 添加数据项 标签方法------
    addTag (rowData) {
      // 先判断 效验输入的值 如果输入的值为空
      if (rowData.addinputValue.trim() === 0) {
        rowData.addinputValue = ''
        rowData.inputVisible = false
        return
      }
      // 把输入的值放在文本框中显示 清空文本框
      rowData.attr_vals.push(rowData.addinputValue.trim())
      rowData.addinputValue = ''
      // 调用新增函数
      this.UpdataTag(rowData)
      rowData.inputVisible = false
    },
    //  删除tag 和新增tag 事件
    async UpdataTag (rowData) {
      // 把数据上传到后台调接口
      const { data: resData } = await this.$http.put(
        `categories/${this.setcateList[2]}/attributes/${rowData.attr_id}`,
        {
          attr_name: rowData.attr_name,
          attr_sel: rowData.attr_sel,
          attr_vals: rowData.attr_vals.join(',')
        }
      )
      if (resData.meta.status !== 200) { return this.$message.error(resData.meta.msg) }
      // 成功
      this.$message.success(resData.meta.msg)
    },
    // 点击按钮隐藏，文本框显示
    showInput (Data) {
      // 走作用域插槽里面 拿点击的属性显示
      Data.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //   获取所有商品分类数据-----
    async getCateList () {
      const { data: resData } = await this.$http.get('categories')
      //   判断是否失败
      if (resData.meta.status !== 200) { return this.$message.error(resData.meta.msg) }
      // 如果成功 1 保存数组
      this.setedCates = resData.data
    },
    // 下拉框和 切换动态静态效果 改变事件函数
    async handleChange () {
      if (this.setcateList.length < 3) {
        // 让下拉框数据为空
        this.setcateList.length = 0
        // 让 动态参数和静态参数 都清空
        this.manyParamsData = []
        this.onlyParamsData = []
      }
      //   选中3级参数 则请求 这个动态参数
      // 获取当前选中的第3级id
      const sanid = this.setcateList[2]
      // 请求接口
      const { data: resData } = await this.$http.get(
        `categories/${sanid}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )

      // 获取小下拉框 数据并循环
      resData.data.forEach((ele) => {
        if (ele.attr_vals) ele.attr_vals = ele.attr_vals.split(',')
        else ele.attr_vals = []
        // 为每一个数据对象加 inputVisible 让每一个数据分开显示哪个添加文本框
        ele.inputVisible = false
        // 当前行的添加框数据对象 这样每一行的数据就不会共用
        ele.addinputValue = ''
      })
      //   如果失败
      if (resData.meta.status !== 200) { return this.$message.error('获取失败,请选择商品分类~~~~') }
      // 如果成功
      // 判断是否为动态还是静态
      if (this.activeName === 'many') {
        this.manyParamsData = resData.data
      } else {
        this.onlyParamsData = resData.data
      }
      // console.log(resData.data)
    },

    // 监听添加对话框关闭事件清空里面的值
    addDialog () {
      this.$refs.addFormRef.resetFields()
    },

    // 确认添加静态属性或者动态属性
    async AddParamsList () {
      // 获取添加属性的 tab 栏 name 值
      this.addForm.attr_sel = this.activeName
      // 获取添加的时候的 ID
      const newid = this.setcateList[2]
      const { data: resData } = await this.$http.post(
        `categories/${newid}/attributes`,
        this.addForm
      )
      // 失败
      if (resData.meta.status !== 201) { return this.$message.error(resData.meta.msg) }
      // 成功
      this.$message.success(resData.meta.msg)
      this.AddParamsVisble = false
      // 添加成功后 渲染
      this.handleChange()
    },
    // 显示对话框修改
    showeditclick (rowData) {
      console.log(rowData)
      this.editParamsVisble = true
      // 把当前的文子渲染到修改数据上
      this.editForm.attr_name = rowData.attr_name
      // 保存当前修改的ID
      this.editForm.attrID = rowData.attr_id
    },
    // 确认修改文本框数据按钮
    async EditParamsList () {
      // 获取选项的3级id
      const catid = this.setcateList[2]
      // 获取当前数据修改的id
      const arrID = this.editForm.attrID
      console.log(arrID, catid)
      // 获取当前 many 或者only 的值
      this.editForm.attr_sel = this.activeName

      const { data: resData } = await this.$http.put(
        `categories/${catid}/attributes/${arrID}`,
        this.editForm
      )
      // 如果失败
      if (resData.meta.status !== 200) { return this.$message.error(resData.meta.msg) }
      // 成功
      this.$message.success(resData.meta.msg)
      this.editParamsVisble = false
      // 重置表单
      this.editForm.attr_name = ''
      this.editForm.attr_sel = ''
      this.editForm.attrID = 0
      this.handleChange()
    },

    // 删除 Tag 事件
    delTag (int, rowData) {
      // 删除数组
      rowData.attr_vals.splice(int, 1)
      // 调入 删除tag 事件
      this.UpdataTag(rowData)
    }
  },
  // 计算属性
  computed: {
    disablebtn () {
      // 必须选中3级参数才可以添加 true为禁用
      return this.setcateList.length !== 3
    },
    // 计算标题文本
    TlietText () {
      if (this.activeName === 'many') {
        return '动态参数 '
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="postcss" scoped>
.el-tag {
  margin: 10px;
}
.el-input {
  width: 120px;
}
</style>
